﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;

namespace T03ChatClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket clientSocket;
        private bool isListen;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            //必须输入昵称,并没有做安全性校检以及政府性校检
            if (string.IsNullOrWhiteSpace(TxtName.Text.Trim()))
            {
                MessageBox.Show("请设置一个聊天昵称");
                return;
            }
            //连接服务器
            if(clientSocket==null)
            {
                try
                {
                    IPAddress ip = IPAddress.Parse("127.0.0.1");
                    IPEndPoint iep = new IPEndPoint(ip, 18888);
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //异步（新开线程），处理网络连接
                    clientSocket.BeginConnect(iep, (args) => {
                        if (args.IsCompleted)
                        {
                            byte[] bytesSend = new byte[4096];
                            //访问UI线程中的内容，异步更新界面
                            TxtName.Dispatcher.BeginInvoke(new Action(() => {
                                bytesSend = Encoding.UTF8.GetBytes(TxtName.Text.Trim() + "$");
                                //如果连接上，设置相关界面
                                if (clientSocket != null && clientSocket.Connected)
                                {
                                    clientSocket.Send(bytesSend);
                                    TxtName.IsEnabled = false;
                                    TxtSendMsg.Focus();
                                    //启动连接线程
                                    Thread t = new Thread(DataFormServer);
                                    t.IsBackground = true;
                                    t.Start();
                                }
                                else
                                {
                                    MessageBox.Show("服务器已关闭");
                                    clientSocket = null;
                                }
                            }));
                        }
                    }, null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("已连接服务器");
            }
        }

        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
         
            if (string.IsNullOrWhiteSpace(TxtSendMsg.Text.Trim())){
                MessageBox.Show("不能发送空内容!");
                return;
            }
            if (clientSocket != null && clientSocket.Connected)
            {
                byte[] bytesSend = Encoding.UTF8.GetBytes(TxtSendMsg.Text + "$");
                clientSocket.Send(bytesSend);
                TxtSendMsg.Text = "";
            }
            else
            {
                MessageBox.Show("服务器连接已关闭或未连接");
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            //文本发送框焦点
            TxtSendMsg.Focus();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (clientSocket != null && clientSocket.Connected)
            {
                //告知服务器断开连接
                clientSocket.Send(Encoding.UTF8.GetBytes("$"));
            }
        }

        private void DataFormServer()
        {
            ShowMsg("连接到聊天服务器。。。");
            isListen = true;
            try
            {
                while (isListen)
                {
                    byte[] bytesFrom = new byte[4096];
                    int len = clientSocket.Receive(bytesFrom);
                    string dataFromSrever = Encoding.UTF8.GetString(bytesFrom, 0, len);
                    //用户名已存在
                    if (dataFromSrever.StartsWith("#") && dataFromSrever.EndsWith("#"))
                    {
                        string username = dataFromSrever.Substring(1, dataFromSrever.Length - 2);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MessageBox.Show("用户名【" + username + "】已存在，请重新输入");
                            TxtName.IsEnabled = true;
                            TxtName.Focus();
                        }));
                        isListen = false;
                        //用户名重复后，中断连接
                        if (clientSocket != null && clientSocket.Connected)
                        {
                            clientSocket.Send(Encoding.UTF8.GetBytes(TxtSendMsg.Text + "$"));
                            clientSocket.Close();
                            clientSocket = null;
                        }
                    }
                    else
                    {
                        //显示信息
                        ShowMsg(dataFromSrever);
                    }
                }
            }
            catch (Exception e)
            {

                isListen = false;
                if (clientSocket != null && clientSocket.Connected)
                {
                    clientSocket.Send(Encoding.UTF8.GetBytes("$"));
                    Debug.WriteLine(e.ToString());
                }
            }
        }

        private void ShowMsg(string msg)
        {
            TxtReciveMsg.Dispatcher.BeginInvoke(new Action(() =>
            {
                TxtReciveMsg.Text += Environment.NewLine + msg;
                TxtReciveMsg.ScrollToEnd();
            }));
        }
    }
}
